package pinyinJava.executors;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import pinyinJava.bean.DBean;
import pinyinJava.utils.TimerUtil;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class PyExecutor {

    private final ExecutorService executorService = Executors.newFixedThreadPool(20);
    private String baseUrl;
    private final AtomicInteger atomicInteger = new AtomicInteger(0);
    private int total;

    public PyExecutor(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public void getPy() throws IOException {
        Document document = Jsoup.parse(new URL(baseUrl + "pinyi.html").openStream(), "gbk", baseUrl + "pinyi.html");
        Elements elements = document.select("td[class$=font_14],p[class$=font_14]");
        Elements elements1 = document.select("a[class$=fontbox]");
        total = elements.size();
        TimerUtil.start(atomicInteger, total, executorService);
        for (Element element : elements) executorService.execute(new MyRun(this, element, elements1, atomicInteger));
    }

    public void getWord(Element element, ArrayList<DBean> words, ArrayList<DBean> phrases) throws IOException {
        Document document = Jsoup.parse(new URL(baseUrl + element.attr("href")).openStream(), "gbk", baseUrl + element.attr("href"));
        Elements elements = document.select("a[class$=fontbox]");
        for (Element element1 : elements) {
            DBean word = new DBean(element.text().replace("ü", "v"), element1.text().substring(0, 1));
            words.add(word);
            getPhrases(element1, word, phrases);
        }
    }

    public void getPhrases(Element element, DBean word, ArrayList<DBean> phrases) throws IOException {
        Document document = Jsoup.parse(new URL(baseUrl + element.attr("href")).openStream(), "gbk", baseUrl + element.attr("href"));
        Elements elements = document.select("a[href^=/html5]");
        for (Element element1 : elements) {
            if (element1.text().startsWith(word.getWord())) {
                DBean word1 = new DBean(word.getCode(), element1.text());
                phrases.add(word1);
            }
        }
    }
}
